package com.open.cloud.datasource.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import com.open.cloud.common.context.ContextUserDetails;
import com.open.cloud.common.context.UserDetailsContextHolder;
import com.open.cloud.datasource.properties.MybatisPlusProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 *
 * mybatis-plus自动配置
 *
 * @author kong
 * @date 2021/2/12
 * blog: http://blog.kongyin.ltd
 */
@EnableConfigurationProperties(MybatisPlusProperties.class)
public class MybatisPlusAutoConfigure {

    @Autowired
    private MybatisPlusProperties mybatisPlusProperties;

    /**
     * 默认操作用户ID
     */
    private final String DEFAULT_OPERATION_USER_ID = "1";

    /**
     * 配置mybatis plus 分页拦截器配置
     *
     * @return
     */
    @ConditionalOnMissingBean(PaginationInterceptor.class)
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();

        // 设置请求的页面大于最大页后操作， true调回到首页，false 继续请求  默认false
        boolean overflow = mybatisPlusProperties.isOverflow();
        paginationInterceptor.setOverflow(overflow);

        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        long limit = mybatisPlusProperties.getLimit();
        paginationInterceptor.setLimit(limit);

        // 开启count的join优化，只针对部分left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));

        //TODO 租户
        return paginationInterceptor;
    }

    /**
     * 默认字段自动维护配置
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(MetaObjectHandler.class)
    @ConditionalOnProperty(prefix = "opc-frame.mybatis-plus", name = "enabled", havingValue = "true", matchIfMissing = true)
    public MetaObjectHandler defaultMetaObjectHandler() {
        return new AbstractBaseMetaObjectHandler(mybatisPlusProperties) {
            @Override
            public String getOperatorId() {
                ContextUserDetails contextUserDetails = UserDetailsContextHolder.getContextUserDetails(true);
                return contextUserDetails != null ? contextUserDetails.getId() : DEFAULT_OPERATION_USER_ID;
            }
        };
    }
}
